﻿using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DBModel.EntityExtension
{
    public static class SqlSugarContextExtension
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="services"></param>
        /// <param name="dbConn">"server=localhost;Database=tsdb2;Uid=root;Pwd=111111;"</param>
        /// <param name="dbType">数据库类型</param>
        /// <param name="autoCloseConnection">是否自动关闭连接</param>
        /// <returns></returns>
        public static IServiceCollection AddSqlSugarContextPool(
            this IServiceCollection services,
            string dbConn,
            DbType dbType,
            bool autoCloseConnection = true
            )
        {
            services.AddScoped<ISqlSugarClient>(s =>
            {
                SqlSugarClient sqlSugar = new SqlSugarClient(new ConnectionConfig()
                {
                    DbType = dbType,
                    ConnectionString = dbConn,
                    IsAutoCloseConnection = autoCloseConnection,
                },
                db =>
                {
                    // 单例参数配置，所有上下文生效
                    db.Aop.OnLogExecuting = (sql, pars) =>
                    {
                        Console.WriteLine(sql, pars);
                        //获取IOC对象不要求在一个上下文
                        //var log = s.GetService<Log>();
                        //获取IOC对象要求在一个上下文
                        //var appServive = s.GetService<IHttpContextAccessor>();
                        //var log= appServive?.HttpContext?.RequestServices.GetService<Log>();
                    };
                });
                //sqlSugar.Aop.OnLogExecuting = (sql, pars) => { Console.WriteLine(sql, pars); };
                return sqlSugar;
            });

            return services;
        }
    }
}